<template>
  <div>
    <el-alert
            :closable="false"
            title="温馨提醒"
            type="warning"
            :description="tips">

    </el-alert>
    <!-- 搜索 -->
    <el-form :model="formItem"  label-width="80px" :inline="true" class="demo-form-inline" style="padding-top: 10px;">
      <el-form-item label="关键字">
        <el-input v-model="formItem.keyword" placeholder="题目" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="searchSubmit('formItem')">搜索</el-button>
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 10px;">
      <el-button @click.native="addQuestion()" type="primary" size="mini">添加</el-button>
      <el-button @click.native="deleteAll()" type="danger" size="mini">删除</el-button>
      <el-button @click.native="importResult()" type="primary" size="small" icon="el-icon-download">导入结果</el-button>
      <el-upload style="display: inline;"
                 :action="questionUpload"
                 :before-upload="beforeUpload"
                 :headers="headers"
      >
        <el-button size="small" type="primary">导入</el-button>
      </el-upload>
    </div>
    <el-table ref="selection" :data="listData" border tooltip-effect="dark" style="width: 100%"  @cell-dblclick="tableEdit" @selection-change="select">
      <el-table-column fixed type="selection" width="55"></el-table-column>
      <el-table-column prop="title" label="题目" width="500"></el-table-column>
      <el-table-column prop="answer" label="答案" width="200"></el-table-column>
      <el-table-column label="状态" width="200">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status"
                     active-color="#00A854"
                     active-text="显示"
                     :active-value="1"
                     class="demo"
                     inactive-color="#F04134"
                     inactive-text="隐藏"
                     :inactive-value="2"
                     @change="changeSwitch(scope.$index)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="200">
        <template slot-scope="scope">{{ scope.row.sort }}</template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button @click.native.prevent="edit(scope.$index)" type="primary" size="mini">编辑</el-button>
          <el-button @click.native.prevent="del(scope.$index)" type="danger" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="text-align : right; float : right; margin-top: 10px;">
      <!--<span class="demonstration">完整功能</span>-->
      <el-pagination
              @size-change="handlePageSize"
              @current-change="handlePage"
              :current-page="pageNum"
              :page-sizes="[10, 50, 100, 200]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageTotal">
      </el-pagination>
    </div>
    <!-- 题添加修改 -->
    <el-dialog :visible.sync="questionModal" :title="titleStr" width="75%">
      <el-form ref="activity" :model="formAdd" :rules="formAddValidate" label-width="80px" class="demo-ruleForm">
        <el-form-item label="题目" prop="title">
          <el-input v-model="formAdd.title" style="width:600px;" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="正确答案" prop="answer">
          <el-input v-model="formAdd.answer" style="width:300px;"  placeholder="请输入正确答案"></el-input>
        </el-form-item>
        <div>
          <el-button type="primary" size="mini" @click="addArray">添加</el-button>
          <div v-for="(a,index) in arrayData" :key="index" style="display: flex;justify-content: flex-start;position: relative">
            <el-form-item  label="选项" prop="options">
              <el-input v-model="a.option" placeholder="请输入选项"></el-input>
            </el-form-item>
            <el-form-item  label="内容" prop="options">
              <el-input v-model="a.content" placeholder="请输入内容"></el-input>
            </el-form-item>
            <el-form-item  >
              <el-button type="danger" size="mini" @click="delArray(index)">删除</el-button>
            </el-form-item>
          </div>
        </div>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formAdd.sort" :min="1" :max="10000" style="width:300px;"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.native="questionSubmit('formAdd')">提交</el-button>
          <el-button @click="questionCancel()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import axios from "@/axios";
import { isIntNum,getHeaders } from "@/assets/js/common";
import moment from 'moment'
export default {
  data() {
    return {
      tips: '',
      questionModal: false,
      imgUrl: "",
      formItem: {
        keyword: "",
      },
      titleStr: '',
      formAdd: {
        title: "",
        answer: "",
        sort: 1
      },
      formAddValidate: {
        title: [
          {
            required: true,
            message: "题目不能为空",
            trigger: "change"
          }
        ],
        answer: [
          {
            required: true,
            message: "答案不能为空",
            trigger: "change"
          }
        ]
      },
      ids: [],
      listData: [],
      pageTotal: 0,
      pageNum: 1,
      pageSize: 10,
      headers: {},
      credentials: true,
      questionUpload: "",
      arrayData:[{
        option:'',
        content:''
      }],
    };
  },
  mounted() {
    this.base = JSON.parse(sessionStorage.base);
    this.questionUpload = this.base.domain_name + '/admin/question/import';
    this.tips="题库导入模板下载地址：" + this.base.domain_name + '/template/question_import_demo.xlsx';
    this.headers = getHeaders(localStorage._token);
    // 题列表
    this.getQuestion();
  },
  methods: {
    beforeUpload(file) {
      const isJPG = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      const isLt2M = file.size / 1024 / 1024 < 50;

      if (!isJPG) {
        this.$message.error('上传文件只能是 excel 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 50MB!');
      }
      return isJPG && isLt2M;
    },
    //  数组删除
    delArray(index){
      if(this.arrayData.length == 1){
        return
      }
      this.arrayData.splice(index,1)
    },
    //   数组添加
    addArray(){
      let params = {
        option:'',
        content:''
      };
      let index = this.arrayData.length;
      // 追加数组
      this.$set(this.arrayData,index,params);
    },
    tableEdit(row, column, cell, event) {
      let vm = this;
      if (column.label) {
        // 获取当前的值
        var beforeVal = event.target.textContent;
        event.target.innerHTML = "";
        let str = `<div class='cell'>
            <div class='el-input'>
              <input type='text' placeholder='请输入内容' class='el-input__inner'>
            </div>
        </div>`;
        cell.innerHTML = str;
        // 获取双击后生成的input  根据层级嵌套会有所变化
        let cellInput = cell.children[0].children[0].children[0];
        cellInput.value = beforeVal;
        cellInput.focus(); // input自动聚焦
        // 失去焦点后  将input移除
        cellInput.onblur = function() {
          let onblurCont = `<div class='cell'>${cellInput.value}</div>`;
          cell.innerHTML = onblurCont; // 换成原有的显示内容
          // 调用axios接口
          if (column.property === 'sort'){
            axios
              .post("/admin/question/updateSort", {
                id: row.id,
                sort: cellInput.value
              })
              .then(response => {
                let status = response.status;
                let data = response.data;
                if (data.code === 200) {
                  vm.$message({
                    type: 'success',
                    message: "操作成功!",
                    onClose: function (msg) {
                      vm.getQuestion();
                    }
                  });
                } else {
                  vm.$message.info(data.message);
                }
              })
              .catch(error => {
                // vm.$Message.info("网络或服务器异常");
              });
          }
        };
      }
    },
    //获取勾选参数
    select(val) {
      let vm = this;
      vm.ids = [];
      for (let i in val) {
        vm.ids.push(val[i].id);
      }
    },
    //当前页数
    handlePage(value) {
      this.pageNum = value;
      this.getQuestion();
    },
    //每页显示条数
    handlePageSize(value) {
      this.pageSize = value;
      this.getQuestion();
    },
    //获取文章列表
    getQuestion() {
      let vm = this;
      axios
        .post("/admin/question/lists", {
          page: this.pageNum,
          limit: this.pageSize,
          keyword: this.formItem.keyword
        })
        .then(response => {
          let status = response.status;
          let data = response.data;
          if (data.code == 200) {
            let result = data.data;
            vm.pageTotal = result.total;
            vm.listData = result.list;
          } else {
            vm.$message.info(data.message);
          }
        })
        .catch(error => {
          // vm.$Message.info("网络或服务器异常");
        });
    },
    //更改状态
    changeSwitch(index) {
      let vm = this;
      if (this.listData[index].status == 1) {
        status = 2;
      } else {
        status = 1;
      }
      axios
        .post("/admin/question/updateStatus", {
          id: vm.listData[index].id,
          status: status
        })
        .then(response => {
          let status = response.status;
          let data = response.data;
          if (data.code == 200) {
            this.$message({
              message: '操作成功!',
              type: 'success',
              onClose: function(msg) {
                vm.getQuestion();
              }
            });
          } else {
            vm.$message.error(data.message);
          }
        })
        .catch(error => {
          // vm.$message.info("网络或服务器异常");
        });
    },
    //删除
    del: function (index = "") {
      let vm = this;
      //判断单条多条操作
      vm.ids = [];
      if (!isIntNum(index)) {
        vm.ids.push(vm.listData[index].id);
      } else {
        if (vm.ids.length < 1) {
          vm.$message.error("请勾选数据！");
          return false;
        }
      }
      this.$confirm("是否确认删除吗？", "确认删除" , {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios
          .post("/admin/question/delete", {
            ids: vm.ids
          })
          .then(response => {
            let status = response.status;
            let data = response.data;
            if (data.code == 200) {
              vm.$message({
                type: 'success',
                message: "操作成功!",
                onClose: function (msg) {
                  vm.getQuestion();
                  vm.ids = [];
                }
              });
            } else {
              vm.$message.error(data.message);
            }
          })
          .catch(error => {
            //vm.$Message.info("网络或服务器异常");
          });
      }).catch(() => {
        vm.ids = [];
        this.$refs.selection.selectAll(false);
      });
    },
    // 添加
    addQuestion() {
      this.titleStr = '添加';
      this.questionModal = true;
    },
    // 活动添加、编辑处理
    questionSubmit(name) {
      let vm = this;
      vm.formAdd.options = this.arrayData;
      this.$refs.activity.validate(valid => {
        if (valid) {
          axios
            .post("/admin/question/store", vm.formAdd)
            .then(response => {
              let status = response.status;
              let data = response.data;
              if (data.code == 200) {
                vm.questionModal = false;
                vm.formAdd.id = "";
                vm.formAdd.answer = "";
                vm.formAdd.title = "";
                vm.formAdd.sort = 1;
                vm.arrayData = [{
                  option:'',
                  content:''
                }];
                vm.$message({
                  type: 'success',
                  message: "操作成功!",
                  onClose: function (msg) {
                    vm.getQuestion();
                  }
                });
              } else {
                vm.$message.error(data.message);
              }
            })
            .catch(error => {
              // console.log(error);
              // vm.$message.error("网络或服务器异常");
            });
        } else {
          // vm.$message.error("Fail!");
        }
      });
    },
    // 编辑
    edit(index) {
      this.titleStr = '编辑';
      this.questionModal = true;
      this.formAdd = this.listData[index];
      this.arrayData = this.listData[index].options;
    },
    // 弹窗取消
    questionCancel() {
      this.questionModal = false;
      this.formAdd.id = "";
      this.formAdd.title = "";
      this.formAdd.answer = "";
      this.arrayData = [{
        option:'',
        content:''
      }];
      this.formAdd.sort = 1;
      this.getQuestion();
    },
    //搜索
    searchSubmit() {
      this.pageNum = 1;
      this.getQuestion();
    },
    // 批量删除
    deleteAll() {
      let vm = this;
      if (vm.ids.length < 1) {
        vm.$message.error("请勾选数据！");
        return false;
      }
      this.$confirm("是否确认删除吗？", "确认删除" , {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios
          .post("/admin/question/delete", {
            ids: vm.ids
          })
          .then(response => {
            let status = response.status;
            let data = response.data;
            if (data.code == 200) {
              vm.$message({
                type: 'success',
                message: "操作成功!",
                onClose: function (msg) {
                  vm.getQuestion();
                  vm.ids = [];
                }
              });
            } else {
              vm.$message.error(data.message);
            }
          })
          .catch(error => {
            //vm.$Message.info("网络或服务器异常");
          });
      }).catch(() => {
        vm.ids = [];
        this.$refs.selection.selectAll(false);
      });
    },
    // 导入结果
    importResult() {
      this.$router.push({
        path: "question_import"
      });
    },
  }
};
</script>